package com.yanqu.road.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.api.test.JobManager;
import com.yanqu.road.api.test.TestJob;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * wmm
 * 2023/2/5
 */
@Controller
@RequestMapping("/job")
public class TestJobController {

    static Logger logger = LoggerFactory.getLogger(TestJobController.class);

    @GetMapping(value = "/index")
    public String index(){
        return "test";
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public String list(){
        JSONArray array = new JSONArray();
        for (Map.Entry<Long, TestJob> entry : JobManager.getJobMap().entrySet()) {
            TestJob job = entry.getValue();
            JSONObject object = getJobInfoJson(job);
            array.add(object);
        }
        return array.toJSONString();
    }

    private JSONObject getJobInfoJson(TestJob job) {
        JSONObject object = new JSONObject();
        object.put("jobId", job.getJobId());
        object.put("userId", job.getUserId());
        object.put("openId", job.getOpenId());
        object.put("state", job.getJobState().getStatus());
        object.put("stateName", job.getJobState().getName());
        object.put("login", job.isLogin());
        return object;
    }

    @PostMapping("/newJob/{userId}")
    @ResponseBody
    public String newJob(@PathVariable("userId") long userId){
        if(TestJob.getApiList().size() == 0){
            return "{}";
        }
        //查下openId
        UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
        if(userInfo == null){
            return "{}";
        }
        TestJob job = JobManager.newJob(userId);
        job.setOpenId(userInfo.getOpenId());
        JSONObject result = getJobInfoJson(job);
        return result.toJSONString();
    }

    @PostMapping("/start/{jobId}")
    @ResponseBody
    public String startJob(@PathVariable("jobId") long jobId){
        JSONObject result = new JSONObject();
        TestJob job = JobManager.getJobById(jobId);
        if(job != null) {
            job.start();
            result.put("ret", true);
            result.put("jobId", jobId);
        }else {
            result.put("ret", false);
        }
        return result.toJSONString();
    }

    @PostMapping("/call")
    @ResponseBody
    public String callJob(HttpServletRequest request, @RequestBody String body){
        JSONObject result = new JSONObject();
        JSONArray jobId = new JSONArray();
        JSONArray array = JSONArray.parseArray(body);
        boolean loop = "loop".equalsIgnoreCase(request.getParameter("loop"));

        if(array != null && array.size() > 0){
            for (Object o : array) {
                JSONObject obj = (JSONObject)o;
                long userId = obj.getLong("userId");
                int code = obj.getInteger("code");
                TestJob job = JobManager.getJobByUserId(userId);
                if(job != null) {
                    result.put("ret", true);
                    jobId.add(job.getJobId());
                    JSONObject param = obj.getJSONObject("params");
                    ArrayList<String> keys = new ArrayList<>(param.keySet());
                    for (String key : keys) {//过滤没传值的字段
                        String value = param.getString(key);
                        if (StringUtils.isNullOrEmpty(value)) {
                            param.remove(key);
                        }
                    }
                    String json = param.toJSONString();
                    byte[] datas = job.buildReqParamsForByte(json, code);
                    YanQuMessage message = YanQuMessageUtils.buildMessageByte(code, userId, datas);
                    job.write(message);
                    logger.info("{}", message);
                    if(loop){
                        JobManager.addJobRunningMessage(job.getJobId(), message);
                    }
                }
            }
            result.put("jobId", jobId);
        }else {
            result.put("ret", false);
        }
        return result.toJSONString();
    }

    @GetMapping("/jobResult/{jobId}")
    @ResponseBody
    public String jobResult(HttpServletRequest request, @PathVariable("jobId") long jobId){

        List<String> list = JobManager.getMessageMap().get(jobId);
        if(list != null){
            List<String> result = null;
            synchronized (list){
                if(list.size() > 0){
                    result = new ArrayList<>(list);
                    list.clear();
                }
            }
            if(result != null){
                JSONObject obj = new JSONObject();
                obj.put("jobId", jobId);
                JSONArray ret = new JSONArray();
                for (String s : result) {
                    JSONObject object = JSONObject.parseObject(s);
                    ret.add(object);
                }
                obj.put("result", ret);
                return obj.toJSONString();
            }
        }
        return "{}";
    }

    @PostMapping("/del")
    @ResponseBody
    public String delJob(@RequestParam("jobId") String jobId){
        List<Long> jobIdList = StringUtils.stringToLongList(jobId, ",");
        List<Long> delList = new ArrayList<>();
        for (long id : jobIdList) {
            TestJob job = JobManager.getJobById(id);
            if(job != null){
                job.logout();
                job.stop();
                JobManager.removeJob(id);
                logger.info("del job {}", id);
                delList.add(id);
            }
        }
        JSONObject result = new JSONObject();
        result.put("ret", true);
        result.put("jobList", StringUtils.listToString(delList, ","));
        return result.toJSONString();
    }

    @PostMapping("/pause")
    @ResponseBody
    public String pauseJob(@RequestParam("jobId") String jobId){
        List<Long> jobIdList = StringUtils.stringToLongList(jobId, ",");
        List<Long> pauseList = new ArrayList<>();
        for (long id : jobIdList) {
           List<YanQuMessage> list = JobManager.getJobMessageMap().remove(id);
           if(list != null){
               pauseList.add(id);
           }
        }
        JSONObject result = new JSONObject();
        result.put("ret", true);
        result.put("jobList", StringUtils.listToString(pauseList, ","));
        return result.toJSONString();
    }

}
